import React, { useState } from "react";
import type { CascaderProps } from "antd";
import { Cascader } from "antd";
import { useAsyncEffect } from "ahooks";
import { enumValuesAtom } from "@/store/enum";
import { useAtomValue } from "jotai";
import request from "@/services/interceptors";

interface Option {
  value?: string | number;
  label?: string;
  children?: Option[];
  isLeaf?: boolean;
  level: number;
}

const StudentClass: React.FC = ({ value, onChange }) => {
  const { gradeList } = useAtomValue(enumValuesAtom);
  const [options, setOptions] = useState<Option[]>();

  useAsyncEffect(async () => {
    setOptions(() => {
      return gradeList?.map((grade) => {
        return {
          label: `${grade.label}年级`,
          value: grade.value,
          isLeaf: false,
          level: 1,
          children: [],
        };
      });
    });
  }, [gradeList]);

  // const onChange: CascaderProps<Option>["onChange"] = (
  //   value,
  //   selectedOptions
  // ) => {
  //   console.log(value, selectedOptions);
  // };
  // /sgks/class/teamList
  const loadData = async (selectedOptions: Option[]) => {
    const targetOption: any = selectedOptions[selectedOptions.length - 1];
    if (targetOption.level === 1) {
      const res: any = await request.sgks.classTeamListList({
        grade: targetOption.value,
      } as any);
      const children = [...new Set(res.data)]?.map((item) => ({
        label: `${item}队`,
        value: item,
        isLeaf: false,
        level: 2,
      }));
      if (children?.length) {
        targetOption.children = children;
      } else {
        targetOption.isLeaf = true;
      }
    }
    if (targetOption.level === 2) {
      const res: any = await request.sgks.classUnitListList({
        grade: selectedOptions[0].value,
        classTeam: selectedOptions[1].value,
      } as any);
      targetOption.children = [...new Set(res.data)]?.map((item) => ({
        label: `${item}区队`,
        value: item,
        isLeaf: true,
        level: 3,
      }));
    }
    setOptions([...options]);
  };

  return (
    <Cascader
      value={value}
      options={options}
      loadData={loadData}
      onChange={onChange}
      changeOnSelect
    />
  );
};

export default StudentClass;
